from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer

import json
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
import random

from user.models import UserModel
from utils.MyRedis import r

userlist = []


def process_string(input_string, userstr):
    index = input_string.find(userstr)
    if index != -1:
        return input_string[index + len(userstr):]
    else:
        return None


from ollama import Client


def sendmes(ask):
    client = Client(
        host='http://localhost:11434'  # 大模型所在服务器的地址
    )
    response = client.chat(model='nezahatkorkmaz/deepseek-v3', messages=[
        {
            'role': 'system',
            'content': '你是一个乐于助人的助手'
        },
        {
            'role': 'user',
            'content': ask,
        },
    ])
    print("@@@@")
    print(response['message']['content'])
    return response['message']['content']

class ChatConsumer(WebsocketConsumer):  # 继承WebsocketConsumer
    #    room_name = 'chat_all_data'
    def websocket_connect(self, message):
        print("有人进行连接了。。。。")
        aicode = '1001'
        # cls = ChatConsumer
        # self.room_group_name = cls.room_name
        # print(self.scope['url_route']['kwargs'])
        self.group_name = self.scope['url_route']['kwargs']['group']
        print(self.group_name)
        # user1
        if self.group_name.find('user') >= 0:
            # 用户 user11001
            id = self.group_name[self.group_name.find('user') + len('user'):]
            room = "user" + id + aicode
            user = UserModel.objects.filter(id=id).first()
            async_to_sync(self.channel_layer.group_add)(room, self.channel_name)
            # 当前的用户信息发送给客服{"userid":1,'name':'zs'}

            userid = process_string(room, 'user')

            name = str(userid)
            if name not in userlist:
                channel_layer = get_channel_layer()
                async_to_sync(channel_layer.group_send)(
                    str("1001"),  # 房间组名
                    {
                        'type': 'send_to_chrome',  # 消费者中处理的函数
                        'data': {"id": id, "name": user.username}
                    }
                )
                userlist.append(name)
        else:
            # 客服
            async_to_sync(self.channel_layer.group_add)(str(self.group_name), self.channel_name)
            # self.group_name = "2"
            # async_to_sync(self.channel_layer.group_add)(str(self.group_name), self.channel_name)
            channel_layer = get_channel_layer()
            ulist = r.get_str('userlist')
            if ulist:
                ulist = json.loads(ulist)
                for i in ulist:
                    async_to_sync(channel_layer.group_send)(
                        str(aicode),  # 房间组名
                        {
                            'type': 'send_to_chrome',  # 消费者中处理的函数
                            'data': {"id": i.id, "name": i.name}
                        }
                    )
        # 有客户端向后端发送 WebSocket 连接的请求时，自动触发(握手)
        self.accept()

    def websocket_receive(self, message):
        # 浏览器基于 WebSocket 向后端发送数据，自动触发接收消息
        # 消息持久化 mysql  redis
        mes=message['text']
        print('*********')
        # print(message['text'])
        print('*********')
        data = json.loads(message['text'])
        # message = data['mes']
        room = str(data['room']) + '1001'
        answer=sendmes(mes)
        # #    self.send(message)
        # userid = process_string(str(data['room']), 'user')
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            room,  # 房间组名
            {
                'type': 'send_to_chrome',  # 消费者中处理的函数
                'data': {"message": answer, 'from': room}
            }
        )

    def websocket_disconnect(self, message):
        # 客户端向服务端断开连接时，自动触发
        print("连接断开！！")
        self.group_name = self.scope['url_route']['kwargs']['group']

        async_to_sync(self.channel_layer.group_discard)(
            self.group_name,
            self.channel_name
        )
        userlist = []
        raise StopConsumer()

    # 自定义的处理房间组内的数据
    def send_to_chrome(self, event):
        try:
            data = event.get('data')
            # 接收房间组广播数据，将数据发送给websocket
            self.send(json.dumps(data, ensure_ascii=False))
        except Exception as e:
            pass
